<template>
  <div class="vehicle-detail-container container">
    <div v-loading="loading">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/vehicle/list' }">车辆列表</el-breadcrumb-item>
        <el-breadcrumb-item>车辆详情</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 车辆基本信息 -->
      <div class="vehicle-header card">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="14" :lg="16">
            <div class="vehicle-gallery">
              <el-carousel :interval="4000" type="card" height="300px">
                <el-carousel-item v-for="(img, index) in vehicle.images || demoImages" :key="index">
                  <img :src="img" alt="车辆图片" class="carousel-image">
                </el-carousel-item>
              </el-carousel>
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="10" :lg="8">
            <div class="vehicle-info">
              <h1 class="vehicle-title">{{ vehicle.name }}</h1>
              <div class="vehicle-tags" v-if="vehicle.tags && vehicle.tags.length">
                <el-tag v-for="(tag, index) in vehicle.tags" :key="index" :type="getTagType(tag)" size="small">{{ tag }}</el-tag>
              </div>
              <div class="vehicle-meta">
                <div class="meta-item">
                  <span class="label">车型类别：</span>
                  <span class="value">{{ vehicle.type }}</span>
                </div>
                <div class="meta-item">
                  <span class="label">座位数：</span>
                  <span class="value">{{ vehicle.seats }}座</span>
                </div>
                <div class="meta-item">
                  <span class="label">变速箱：</span>
                  <span class="value">{{ vehicle.transmission }}</span>
                </div>
              </div>
              <div class="vehicle-price">
                <div class="price-item">
                  <span class="price-label">日租金：</span>
                  <span class="price-value">¥{{ vehicle.dailyPrice }}/天</span>
                </div>
                <div class="price-item">
                  <span class="price-label">押金：</span>
                  <span class="price-value">¥{{ vehicle.deposit }}</span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 租车表单 -->
      <div class="rental-form card">
        <h2 class="section-title">租车信息</h2>
        <el-form :model="rentalForm" label-width="100px" size="small">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12">
              <el-form-item label="取车日期">
                <el-date-picker
                  v-model="rentalForm.startDate"
                  type="date"
                  placeholder="选择取车日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                  @change="checkAvailability"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="还车日期">
                <el-date-picker
                  v-model="rentalForm.endDate"
                  type="date"
                  placeholder="选择还车日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                  @change="checkAvailability"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item>
            <div class="rental-summary" v-if="rentalDays > 0">
              <div class="summary-item">
                <span class="label">租期：</span>
                <span class="value">{{ rentalDays }}天</span>
              </div>
              <div class="summary-item">
                <span class="label">车辆租金：</span>
                <span class="value">¥{{ rentalAmount }}</span>
              </div>
              <div class="summary-item total">
                <span class="label">总计：</span>
                <span class="value">¥{{ totalAmount }}</span>
              </div>
            </div>
            
            <div class="rental-actions">
              <el-button type="primary" @click="rentNow" :disabled="!isAvailable">立即租车</el-button>
              <span v-if="!isAvailable && rentalDays > 0" class="unavailable-tip">该日期范围内车辆已被预订</span>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 车辆详细信息 -->
      <div class="vehicle-details card">
        <h2 class="section-title">车辆详情</h2>
        <el-tabs>
          <el-tab-pane label="基本配置">
            <div class="features-list">
              <el-row :gutter="20">
                <el-col :xs="12" :sm="8" :md="6" v-for="(feature, index) in vehicle.features || demoFeatures" :key="index">
                  <div class="feature-item">
                    <i class="el-icon-check"></i> {{ feature }}
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 推荐车辆 -->
      <div class="recommended-vehicles card">
        <h2 class="section-title">推荐车辆</h2>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in recommendList" :key="item.id">
            <el-card shadow="hover" class="vehicle-card" @click.native="viewDetail(item.id)">
              <div class="vehicle-image">
                <img :src="item.imageUrl" :alt="item.name">
              </div>
              <div class="vehicle-info">
                <h3 class="vehicle-title">{{ item.name }}</h3>
                <div class="vehicle-meta">
                  <span><i class="el-icon-odometer"></i> {{ item.type }}</span>
                  <span><i class="el-icon-user"></i> {{ item.seats }}座</span>
                </div>
                <div class="vehicle-bottom">
                  <div class="vehicle-price">
                    <span class="price">¥{{ item.dailyPrice }}</span>
                    <span class="unit">/天</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { getVehicleDetail, checkVehicleAvailability, getRecommendVehicles, recordVehicleView } from '@/api/vehicle'

export default {
  name: 'VehicleDetail',
  data() {
    return {
      loading: false,
      vehicle: {},
      rentalForm: {
        startDate: '',
        endDate: ''
      },
      isAvailable: true,
      recommendList: [],
      demoImages: [
        'https://img2.baidu.com/it/u=306367250,2071323421&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=500',
        'https://img0.baidu.com/it/u=4143432741,2799288383&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',
        'https://img1.baidu.com/it/u=1407061519,3367177046&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500'
      ],
      demoFeatures: [
        'GPS导航', '倒车影像', '真皮座椅', '蓝牙音乐', '自动空调', 
        '电动天窗', '定速巡航', '多功能方向盘', 'LED大灯', '电动座椅调节'
      ],
      serviceFee: 50
    }
  },
  computed: {
    rentalDays() {
      if (!this.rentalForm.startDate || !this.rentalForm.endDate) {
        return 0
      }
      
      const startDate = new Date(this.rentalForm.startDate)
      const endDate = new Date(this.rentalForm.endDate)
      const timeDiff = endDate.getTime() - startDate.getTime()
      return Math.ceil(timeDiff / (1000 * 3600 * 24))
    },
    rentalAmount() {
      return this.vehicle.dailyPrice * this.rentalDays
    },
    totalAmount() {
      return this.rentalAmount + this.serviceFee
    }
  },
  created() {
    this.initDateFromQuery()
    this.fetchVehicleDetail()
  },
  methods: {
    initDateFromQuery() {
      const { query } = this.$route
      
      if (query.startDate) {
        this.rentalForm.startDate = query.startDate
      }
      
      if (query.endDate) {
        this.rentalForm.endDate = query.endDate
      }
    },
    async fetchVehicleDetail() {
      this.loading = true
      
      try {
        const id = this.$route.params.id
        const res = await getVehicleDetail(id)
        
        if (res.code === 0 || res.code === 200) {
          this.vehicle = res.data || {}
          
          // 如果后端未返回数据，添加演示数据
          if (!this.vehicle.id) {
            this.addDemoData(id)
          }
          
          // 检查可用性
          this.checkAvailability()
          
          // 获取推荐车辆
          this.fetchRecommendVehicles()
          
          // 记录浏览次数
          this.recordView(id)
        }
      } catch (error) {
        console.error('获取车辆详情失败', error)
        this.$message.error('获取车辆详情失败')
        this.addDemoData(this.$route.params.id)
        this.fetchRecommendVehicles()
      } finally {
        this.loading = false
      }
    },
    addDemoData(id) {
      // 添加演示数据
      this.vehicle = {
        id: id,
        name: '奥迪A6L',
        type: '豪华轿车',
        brand: '奥迪',
        seats: 5,
        transmission: '自动档',
        fuelType: '汽油',
        registrationDate: '2022-01',
        dailyPrice: 399,
        deposit: 5000,
        images: this.demoImages,
        features: this.demoFeatures,
        tags: ['热门', '新车']
      }
    },
    async checkAvailability() {
      if (!this.rentalForm.startDate || !this.rentalForm.endDate || !this.vehicle.id) {
        return
      }
      
      try {
        const res = await checkVehicleAvailability(
          this.vehicle.id,
          this.rentalForm.startDate,
          this.rentalForm.endDate
        )
        
        if (res.code === 0 || res.code === 200) {
          this.isAvailable = res.data.available
        } else {
          this.isAvailable = true // 测试环境默认可用
        }
      } catch (error) {
        console.error('检查车辆可用性失败', error)
        this.isAvailable = true // 测试环境默认可用
      }
    },
    async fetchRecommendVehicles() {
      try {
        const params = {
          vehicleId: this.vehicle.id,
          limit: 4
        }
        
        const res = await getRecommendVehicles(params)
        
        if (res.code === 0 || res.code === 200) {
          this.recommendList = res.data || []
          
          // 如果没有推荐数据，添加演示数据
          if (this.recommendList.length === 0) {
            this.addDemoRecommends()
          }
        }
      } catch (error) {
        console.error('获取推荐车辆失败', error)
        this.addDemoRecommends()
      }
    },
    addDemoRecommends() {
      this.recommendList = [
        {
          id: 2,
          name: '丰田凯美瑞',
          type: '中型轿车',
          seats: 5,
          dailyPrice: 299,
          imageUrl: 'https://img0.baidu.com/it/u=3581278429,1145643938&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500'
        },
        {
          id: 3,
          name: '宝马X5',
          type: 'SUV',
          seats: 5,
          dailyPrice: 599,
          imageUrl: 'https://img0.baidu.com/it/u=935297709,3165513922&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500'
        },
        {
          id: 4,
          name: '别克GL8',
          type: 'MPV',
          seats: 7,
          dailyPrice: 399,
          imageUrl: 'https://img2.baidu.com/it/u=1006327316,1969001512&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500'
        }
      ]
    },
    rentNow() {
      if (!this.rentalForm.startDate || !this.rentalForm.endDate) {
        this.$message.warning('请选择租车日期')
        return
      }
      
      if (!this.isAvailable) {
        this.$message.warning('所选日期车辆已被预订')
        return
      }
      
      this.$router.push({
        path: '/order/create',
        query: {
          vehicleId: this.vehicle.id,
          startDate: this.rentalForm.startDate,
          endDate: this.rentalForm.endDate
        }
      })
    },
    viewDetail(id) {
      if (id === this.vehicle.id) {
        return
      }
      
      this.$router.push({
        path: `/vehicle/detail/${id}`,
        query: {
          startDate: this.rentalForm.startDate,
          endDate: this.rentalForm.endDate
        }
      })
    },
    getTagType(tag) {
      switch (tag) {
        case '热门':
          return 'danger'
        case '新车':
          return 'success'
        case '豪华':
          return 'warning'
        case 'SUV':
        case '商务':
          return 'info'
        case '经济':
          return 'success'
        case '舒适':
          return 'primary'
        default:
          return ''
      }
    },
    // 记录车辆浏览次数
    async recordView(id) {
      try {
        await recordVehicleView(id)
      } catch (error) {
        console.error('记录浏览次数失败', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.vehicle-detail-container {
  padding: 20px 0;
  
  .el-breadcrumb {
    margin-bottom: 20px;
  }
  
  .card {
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
    margin-bottom: 20px;
  }
  
  .section-title {
    font-size: 18px;
    margin-top: 0;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .vehicle-header {
    .vehicle-gallery {
      margin-bottom: 20px;
      
      .carousel-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .vehicle-info {
      .vehicle-title {
        font-size: 24px;
        margin-top: 0;
        margin-bottom: 10px;
      }
      
      .vehicle-tags {
        margin-bottom: 20px;
        
        .el-tag {
          margin-right: 5px;
          margin-bottom: 5px;
        }
      }
      
      .vehicle-meta {
        margin-bottom: 20px;
        
        .meta-item {
          margin-bottom: 10px;
          
          .label {
            color: #606266;
            margin-right: 5px;
          }
          
          .value {
            font-weight: 500;
          }
        }
      }
      
      .vehicle-price {
        padding-top: 20px;
        border-top: 1px dashed #ebeef5;
        
        .price-item {
          margin-bottom: 10px;
          
          .price-label {
            color: #606266;
          }
          
          .price-value {
            font-size: 20px;
            font-weight: bold;
            color: #f56c6c;
            margin-left: 5px;
          }
        }
      }
    }
  }
  
  .rental-form {
    .rental-summary {
      background: #f8f8f8;
      padding: 15px;
      border-radius: 4px;
      margin-bottom: 20px;
      
      .summary-item {
        margin-bottom: 10px;
        
        &.total {
          padding-top: 10px;
          margin-top: 10px;
          border-top: 1px dashed #dcdfe6;
          font-weight: bold;
          
          .value {
            color: #f56c6c;
            font-size: 18px;
          }
        }
        
        .label {
          color: #606266;
          margin-right: 5px;
        }
      }
    }
    
    .rental-actions {
      display: flex;
      align-items: center;
      
      .unavailable-tip {
        margin-left: 15px;
        color: #f56c6c;
      }
    }
  }
  
  .vehicle-details {
    .features-list {
      .feature-item {
        margin-bottom: 15px;
        
        i {
          color: #67c23a;
          margin-right: 5px;
        }
      }
    }
  }
  
  .recommended-vehicles {
    .vehicle-card {
      margin-bottom: 20px;
      cursor: pointer;
      transition: transform 0.3s, box-shadow 0.3s;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
      }
      
      .vehicle-image {
        height: 140px;
        overflow: hidden;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .vehicle-info {
        padding: 15px 0 5px;
        
        .vehicle-title {
          font-size: 16px;
          margin: 0 0 10px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        
        .vehicle-meta {
          display: flex;
          flex-wrap: wrap;
          margin-bottom: 10px;
          color: #666;
          font-size: 13px;
          
          span {
            margin-right: 15px;
            margin-bottom: 5px;
            
            i {
              margin-right: 5px;
            }
          }
        }
        
        .vehicle-bottom {
          .vehicle-price {
            .price {
              font-size: 18px;
              font-weight: bold;
              color: #f56c6c;
            }
            
            .unit {
              font-size: 12px;
              color: #999;
            }
          }
        }
      }
    }
  }
}
</style> 